PROJECT = "httpdemo"
VERSION = "1.0.0"

-- sys库是标配
_G.sys = require("sys")
--[[特别注意, 使用http库需要下列语句]]
_G.sysplus = require("sysplus")

---需要在云编译时添加SPI协议
spi_lcd = spi.deviceSetup(2, 7, 0, 0, 8, 40000000, spi.MSB, 1, 1) -- https://wiki.luatos.com/api/spi.html
-- spi.setup(id, cs, CPHA, CPOL, dataw, bandrate, bitdict, ms, mode)

lcd.init("st7789", {
    port = "device",
    pin_dc = 6,
    pin_pwr = 11,
    pin_rst = 10,
    direction = 0,
    w = 240,
    h = 320,
    xoffset = 0,
    yoffset = 0
}, spi_lcd)
-- 如果显示颜色相反，关闭反色
lcd.invoff()

sys.taskInit(function()

    sys.wait(1000)
    log.info(wlan.init())
    wlan.setMode(wlan.STATION)
    wlan.connect("ESP32", "776654321")

    ---等待wifi连接
    while not wlan.ready() do
        log.info("Disconnection")
        sys.wait(1000)
    end
    log.info("ready !!")

    lcd.setFont(lcd.font_opposansm12_chinese) -- 具体取值可参考api文档的常量表
    while 1 do
        local code, headers, body = http.request("GET",
                                                 "http://quan.suning.com/getSysTime.do")
                                        .wait() -- 留意末尾的.wait()
        time, result = json.decode(body)
        print(body)
        print(result)
        if result==1 then--! 必须对API的结果进行if判断，如果失败的话打印会出错，所以会报错
            log.info(code,time.sysTime2) -- !body的类型时string,time.sysTime2的类型为string
            lcd.drawStr(20, 180, time.sysTime2) -- !使用汉字必须使固件中有汉字的库
        else
            lcd.drawStr(20,180,"http连接失败")
        end

        sys.wait(1000)
        lcd.clear()
    end

end)

-- 用户代码已结束---------------------------------------------
-- 结尾总是这一句
sys.run()
-- sys.run()之后后面不要加任何语句!!!!!
